/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.login.policy;

import com.codemagi.login.model.IUser;
import com.codemagi.servlets.AppException;
import com.codemagi.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Implements IPasswordPolicy to ensure that the password does not contain the username.
 */
public class PasswordUsernamePolicy implements IPasswordPolicy {

    /** 
     * Actually performs the policy check
     */
    public boolean check(IUser user, String newPassword) throws AppException {

	if (user == null) throw new AppException("User is null");

        if (Utils.isEmpty(newPassword)) throw new AppException("Password is null");

	//create case-insensitive regex on the username
	Pattern pattern = Pattern.compile(".*" + user.getUsername() + ".*", Pattern.CASE_INSENSITIVE);
	Matcher matcher = pattern.matcher(newPassword);

	if (matcher.matches()) throw new AppException("Your password cannot contain your username.");
	    
	return true;
    }

}
